package com.weme.common.base


import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.internal.CustomAdapt
import me.jessyan.autosize.utils.ScreenUtils
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VB : ViewBinding, VM : ViewModel> : Fragment(), CustomAdapt {

    protected lateinit var mBinding: VB
    protected lateinit var mContext: Context
    val viewModel: VM by lazy {
        ViewModelProvider(this)[getViewModel()]
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        /*从一个Class对象中，获取该对象父类接收到的参数化类型*/
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val clz = type.actualTypeArguments[0] as Class<*>/*通过反射获取该类下的 inflate 方法*/
            val method = clz.getMethod("inflate", LayoutInflater::class.java)
            mBinding = method.invoke(null, layoutInflater) as VB
        }
        mContext = activity as Context
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (arguments != null) {
            initArgs(arguments)
        }
        startOperate()
        clickListener()

    }

    open fun initArgs(arguments: Bundle?) {}

    abstract fun startOperate()
    abstract fun clickListener()

    /**
     * 获取需要初始化的ViewModel
     */
    protected abstract fun getViewModel(): Class<VM>

    override fun isBaseOnWidth(): Boolean {
        return true
    }

    override fun getSizeInDp(): Float {
        return 360.0F
    }

    fun setScreenWidthHeight() {//适配用的
        val screenSize = ScreenUtils.getScreenSize(requireActivity())
        val width = screenSize[0]
        val height = screenSize[1]
        AutoSizeConfig.getInstance().screenWidth = width
        AutoSizeConfig.getInstance().screenHeight = height
    }
}